
from datetime import date

from django.contrib import auth
from django.core.paginator import Paginator, PageNotAnInteger
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import ListView, DetailView

from post.forms import LoginForm
from post.models import Topic


# Create your views here.

def hello(request):
    return HttpResponse('hello 视图')


def showData(request, urlData):
    d = date.today()
    s = str(d) + "<br>" + urlData
    return HttpResponse(s)

def useRedirect(request):
    # 重定向到之前已定义的视图函数showData
    return redirect('logon')

# @csrf_exempt  # 免除CSRF保护
def login(request):
    if request.method == 'GET':
        # ip_addr = request.META['REMOTE_ADDR']
        # return render(request, 'login.html', {'ip': ip_addr})
        return render(request,
                      'login.html',
                           {'form': LoginForm()})

    elif request.method == 'POST':
        # username = request.POST['username']
        # password = request.POST.get('pwd', '')
        login_form = LoginForm(request.POST)

        if login_form.is_valid():
            data = login_form.cleaned_data

            # if data['username'] == 'admin' \
            #         and data['pwd'] == '123456':
            #     # 登录成功
            #     return redirect('topic_list_page')

            user = auth.authenticate(username=data['username'],
                                     password=data['pwd']) # 不匹配返回None
            if user:
                auth.login(request, user)
                return redirect('topic_list_page')
            else:
                login_form.add_error('username', '登录错误')
                return render(request, 'login.html', {'form': login_form})

        else:
            return render(request, 'login.html', {'form': login_form})

# 20-Form表单进阶-退出登录状态
def logout(req):
    auth.logout(req)
    return redirect('login')

# 欢迎页面函数
def welcome(request):
    return render(request, 'welcome.html')

# 动态路由视图函数(URL参数传递)
def dynamic_hello(request, year, month, day=1): # TODO
    return HttpResponse(
        f'{year}-{month}-{day} Hello Django BBS' # TODO
    )

def hello_template(req):
    return render(req, 'hello_template.html',
                  {'data': '大数据'})

# 14-模板基础-话题列表
def topic_list(req):
    topic_data = Topic.objects.all()

    return render(req, 'post/topic_list.html',
                            {'topics': topic_data})

# 15-类视图CBV-话题列表
class TopicListView(ListView):
    model = Topic # 约定优于(大于)配置
    context_object_name = 'topics'

# 15-类视图CBV-话题详情
class TopicDetailView(DetailView):
    model = Topic

# 14-模板基础-话题列表分页
def topic_list_page(req, page=1):
    PAGE_SIZE = 5

    topic_data = Topic.objects.all()

    paginator = Paginator(topic_data, PAGE_SIZE)

    try:
        topic_data_page = paginator.page(page)
    except PageNotAnInteger:
        topic_data_page = paginator.page(1)

    return render(req,
                    'post/topic_list_page.html',            # 模板页
                         {'topic_count':topic_data.count(), # 数据总量
                            'page_obj': topic_data_page}    # 分页数据
                  )

# 20-Form表单进阶-新增话题

from post.forms import TopicModelForm

def topic_add(request):
    if request.method == 'GET':
        return render(request, 'post/topic_add.html',
                          {'form': TopicModelForm()})

    elif request.method == 'POST':
        topic = TopicModelForm(request.POST)
        if topic.is_valid():
            # topic = Topic.objects.create(title=topic.cleaned_data['title'],
            #                              content=topic.cleaned_data['content'],
            #                              user=request.user)
            # topic = topic.save(commit=False)
            # topic.user = request.user
            topic.save()
            return redirect('topic_list_page')
        else:
            return render(request, 'post/topic_add.html', {'form': topic})
